﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;

namespace TestRabbitMQ
{
    public class RabbitMQConfig
    {

        /// <summary>
        /// 账号
        /// </summary>
        public string UserName { get; set; }
        /// <summary>
        /// 密码
        /// </summary>
        public string Password { get; set; }

        /// <summary>
        /// 设置RabbitMQ服务端地址
        /// </summary>
        public string HostName { get; set; }

        public List<TypeToAttri> Queues { get; set; }

        /// <summary>
        /// 设置消息订阅者
        /// 1、将消费者执行方法集中定义
        /// 2、省去其他多余的反射
        /// </summary>
        /// <param name="assemblyNames">指定包含消息订阅者的程序集</param>
        public void SetAssemblyApplication(List<string> assemblyNames)
        {
            Queues = new List<TypeToAttri>();
            var  assemblys = new List<Assembly>();
            assemblyNames.ForEach(item =>
            {
                var va = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(item));
                assemblys.Add(va);
            });

            assemblys.ForEach(assembly =>//遍历程序集
            {
                var types = assembly.GetTypes();
                var list = types.Where(u => u.IsClass && !u.IsAbstract && !u.IsGenericType).ToList();//获取该程序集中所有类

                foreach (var type in types)
                {
                    var methods = type.GetMethods();
                    var attri = methods.Where(x => x.GetCustomAttributes(typeof(SubscribeAttribute), false).Count() > 0)    //查找调用SubscribeAttribute特性的所有方法
                        .Select(x => new TypeToAttri()
                        {
                            Queue = x.GetCustomAttributes(typeof(SubscribeAttribute), false).FirstOrDefault() as SubscribeAttribute,
                            Method = x,
                            TypeInfo = type
                        })
                        .ToList();
                    if (attri.Count > 0)
                    {
                        Queues.AddRange(attri);
                    }
                }
            });
        }
    }
}
